package com.luo.bbs.front.webapi.service.impl;

import com.example.bbs.front.service.ISignService;
import com.luo.bbs.front.webapi.pojo.UserLoginPrincipal;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class SignServiceImpl implements ISignService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 签到 BitMap
     */
    @Override
    public void sign() {
        Integer userId = getUserId();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + format;
        int dayOfMonth = now.getDayOfMonth();
        //签到成功，返回值为false
        Boolean aBoolean = stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        log.debug("{}",aBoolean);
        //如果是true，Redis已有，说明签到过
        if (BooleanUtils.isTrue(aBoolean)){
            throw new BBSServiceException(ResponseCode.NOT_ACCEPTABLE,"重复签到！");
        }
        log.debug("签到成功");
    }

    @Override
    public boolean isSign() {
        Integer userId = getUserId();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + format;
        int dayOfMonth = now.getDayOfMonth();
        //签到成功，返回值为false,说明还未签到
        Boolean aBoolean = stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        if (BooleanUtils.isFalse(aBoolean)){
            stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, false);
            return false;
        }else {
            return true;
        }

    }


    public UserLoginPrincipal getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginPrincipal principal = (UserLoginPrincipal) authentication.getPrincipal();
        if (principal == null) {
            throw new BBSServiceException(ResponseCode.UNAUTHORIZED, "未登录！");
        }
        return principal;
    }

    public Integer getUserId() {
        if (getUserInfo() == null) {
            return null;
        }
        return getUserInfo().getId();
    }
}
